const app = getApp();
import { zg99Request, hbappRequest } from "/utils/requests";
let fx, gh;
Page({
    /**
     * 组件的初始数据
     */
    data: {
        showModel: false,
        showIcon: !0,
        isShowAuth: !1,
        fenxiao: '',
        gonghao: '',
        actid: 17899,
        form: 17122,
        gonghao: '无',
        fenxiao: '无',
        xiangmu: '2020hbsk',
        item: {},
        laiyuan: '公告',
        percent: 0,
        title: '',
        city: '',
        lx: '',
        filed: {},
        adr: [],
        xianqu: [],
        gangwei: [],
        index1: 0,
        index2: 0,
        index3: 0,
        index4: 0,
        yl: 1,
        xianqu: 'y',
        xm: '',
        bklm: {
            "sk": ['请选择备考岗位', '公务员', '选调生'],
            "sydw": ['请选择备考岗位', '综合岗', '教育岗', '医疗岗'],
            "jstg": ['请选择考试类别', '教师招聘', '特岗教师'],
            "fyjcy": ['请选择考试类别', '法院', '检察院'],
            "all": ['请选择备考方向', '公务员', '事业单位', '教师招聘', '特岗教师', '教师资格', '医疗招聘', '选调生', '金融银行', '农信社', '国企', '三支一扶', '公选/遴选', '书记员', '社区工作者', '学历考试', '招警', '军队文职'],
        },
        nianji: ['请选择年级', '大一', '大二', '大三', '大四', '研一', '研二', '研三'],
        bklxvalue: '',
        title2: '',
        appid: '',
        myPhone: '',
        tuisong: false,
        isShowSetModel: false,
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: async function (options) {
        this.setData(await app.methods.myPhone()); // 获取本地存储手机号
        if(!this.data.myPhone) {
            await app.methods.getPhoneNumber()
        }
        xhs.showLoading({
            title: '数据加载中....',
            mask: true
        })
        xhs.showShareMenu({
          shareTypes: 'normal',
        })
        let links, jxOptions;
        if (options.scene) {
            options.scene = options.scene.replace(/%253D/g, ".");
            options.scene = options.scene.replace(/%2526/g, "-");
            jxOptions = await app.methods.getOPtions(options);
        }
        let id = options.scene ? jxOptions.id : options.id;
        options.id = id;
        links = await app.methods.getLink(id);
        options.xiangmu = links.xiangmu ? links.xiangmu : '';
        options.fx = options.scene ? jxOptions.fx : options.fx;
        options.gh = options.scene ? jxOptions.gh : options.gh;
        if(links.actid) options.actid = links.actid;
        if(links.form) options.form = links.form;
        if (options.actid != undefined) {
            this.setData({
                actid: options.actid,
                form: options.form
            })
        }
        if (options.xiangmu != undefined) {
            this.setData({
                xiangmu: options.xiangmu
            })
        }
        this.setData(await app.methods.getIdentity(options)); // 获取个人身份信息
        if(this.data.getIdentity.crm) {
            options.wxh = this.data.getIdentity.crm;
        } else {
            options.wxh = options.gh;
        }
        this.setData(await app.methods.getWechat(options)); // 获取个人身份信息
        this.setData(await app.methods.guishudi(options)); // 获取归属地
        let fenbu = this.data.fenbu;
        let fenxiao = this.data.fenxiao;
        let getIdentity = this.data.getIdentity;
        getIdentity.fenbu = fenbu;
        getIdentity.fenxiao = fenxiao;
        getIdentity.zzname = this.data.zzname;
        getIdentity.zzid = this.data.zzid;
        getIdentity.erpdqm = this.data.erpdqm;
        this.setData({
            options: options,
            getIdentity: getIdentity
        })
        await this.getHdInfo()
        await this.getXq(this.data.adr[0])
        // 判断项目（gk/sk） 判断类型（ggyy/cjcx） 如果都是，判断给出的templateId数组
        if ((this.data.lx == 'ggyy' || this.data.lx == 'cjcx') && this.data.istuisong == 'y') {
            this.setData({
                tuisong: true
            })
            gh = options.gh;
            fx = options.fx;
        }
        if(this.data.myPhone) {
            this.setData(await app.methods.getphonestatusCX(this.data.myPhone, this.data.form, 'chaxun'))
        }
        xhs.showLoading({
            title: '数据加载完毕！',
        })
        setTimeout(function () {
            xhs.hideLoading()
        }, 1000)
        // console.log(this.data)
    },
    // 获取活动信息
    async getHdInfo() {
        return new Promise((resolve, reject) => {
            zg99Request({
                url: `/index/chaxun/getfzinfo/?actid=${this.data.actid}&callback=&`,
                method: "GET",
                dataType: 'jsonp',
                data: {
                    tabnum: 2,
                    xiangmu: this.data.xiangmu,
                    shijian: Date.parse(new Date()) / 1000
                },
            }).then(res => {
                let newStr = app.methods.getAPIReturn(res);
                // console.log(newStr)
                let title = newStr.lists[0].title;
                if (title.indexOf(',') >= 0) {
                    title = title.split(',')
                    this.setData({
                        title: title[0],
                        title2: title[1],
                    })
                } else {
                    this.setData({
                        title: title,
                    })
                }
                this.setData({
                    lx: newStr.lists[0].lx,
                    xm: newStr.lists[0].xm,
                    nj: newStr.lists[0].nianji,
                    city: newStr.lists[0].city,
                    url: newStr.lists[0].url,
                    isxq: newStr.lists[0].isxq,
                    notice: newStr.lists[0].notice,
                    appid: newStr.lists[0].appid,
                    iszhuanye: newStr.lists[0].iszhuanye,
                    istuisong: newStr.lists[0].istuisong,
                    form: Number(newStr.lists[0].form),
                })
                let ly = '';
                this.data.lx == 'ggyy' ? (
                    xhs.setNavigationBarTitle({
                        title: this.data.title + '公告预约',
                    }, ly = this.data.title + '公告预约')
                ) : this.data.lx == 'cjcx' ? (
                    xhs.setNavigationBarTitle({
                        title: this.data.title + '成绩查询',
                    }, ly = this.data.title + '公告预约')
                ) : (
                    xhs.setNavigationBarTitle({
                        title: this.data.title + this.data.title2,
                    }, ly = this.data.title + '公告预约')
                )
                app.globalData.laiyuan = ly
                var newArr = [];
                if (this.data.city == 'sjz') {
                    newArr.push('石家庄市');
                } else if (this.data.city == 'bd') {
                    newArr.push('保定市')
                } else if (this.data.city == 'ts') {
                    newArr.push('唐山市')
                } else if (this.data.city == 'hd') {
                    newArr.push('邯郸市')
                } else if (this.data.city == 'qhd') {
                    newArr.push('秦皇岛市')
                } else if (this.data.city == 'xt') {
                    newArr.push('邢台市')
                } else if (this.data.city == 'lf') {
                    newArr.push('廊坊市')
                } else if (this.data.city == 'cz') {
                    newArr.push('沧州市')
                } else if (this.data.city == 'cd') {
                    newArr.push('承德市')
                } else if (this.data.city == 'hs') {
                    newArr.push('衡水市')
                } else if (this.data.city == 'zjk') {
                    newArr.push('张家口市')
                } else if (this.data.city == 'tj') {
                    newArr.push('天津市')
                } else {
                    newArr = ["石家庄市", "保定市", "唐山市", "承德市", "邯郸市", "沧州市", "秦皇岛市", "张家口市", "廊坊市", "衡水市", "邢台市"]
                }
                this.setData({
                    adr: newArr
                })
                if ((this.data.xm == 'sk') || (this.data.xm == 'sydw') || (this.data.xm == 'jztg') || (this.data.xm == 'fyjcy') || (this.data.xm == 'all')) {
                    this.setData({
                        gangwei: this.data.bklm[this.data.xm]
                    })
                }
                resolve()
            }).catch(err => {
                reject()

            })
        })
    },
    // 获取县区
    async getXq(grtext) {
        return new Promise((resolve, reject) => {
            zg99Request({
                url: `/index/chaxun/getlevel?actid=${this.data.actid}&callback=&`,
                type: 'GET',
                dataType: 'jsonp',
                data: {
                    level: '2',
                    'grfiled': 'adr',
                    grtext: grtext,
                    shijian: Date.parse(new Date()) / 1000
                },
            }).then(res => {
                let newStr = app.methods.getAPIReturn(res);
                // console.log(newStr)
                var newArr = [];
                for (var i = 0; i < newStr.lists.length; i++) {
                    newArr.push(newStr.lists[i].xianqu)
                }
                this.setData({
                    xianqu: newArr
                })
                resolve()
            }).catch(err => {
                console.log(err)
            })
        })
    },
    // 选择事件
    bindPickerChange: function (e) {
        if (e.currentTarget.dataset.method == 'adr') {
            // 选择地市
            this.setData({
                index1: e.detail.value
            })
            this.getXq(this.data.adr[e.detail.value])
        } else if (e.currentTarget.dataset.method == 'xianqu') {
            // 选择县区
            this.setData({
                index2: e.detail.value
            })
        } else if (e.currentTarget.dataset.method == 'gangwei') {
            // 选择岗位
            this.setData({
                index3: e.detail.value
            })
        } else if (e.currentTarget.dataset.method == 'nianji') {
            // 选择年级
            this.setData({
                index4: e.detail.value
            })
        }
    },
    //姓名
    nameChange: function (e) {
        this.setData({
            name: e.detail.value
        })
        if (!this.data.name) {
            xhs.showToast({
                title: '请输入您的昵称',
                icon: 'none',
                duration: 1000
            })
            return false;
        }
    },
    getname(e) {
        // console.log(e)
        this.setData({
            name: e.detail.value
        })
      },
    //专业
    zhuanyeChange: function (e) {
        this.setData({
            zhuanye: e.detail.value
        })
        if (!this.data.zhuanye) {
            xhs.showToast({
                title: '请输入专业',
                icon: 'none',
                duration: 1000
            })
            return false;
        }
    },
    // 预约
    clickfn: async function (e) {
        if (!this.data.myPhone) {
            this.setData({
                isShowAuth: !0,
            })
            return false;
        }
        if (!this.data.name) {
            xhs.showToast({
                title: '请输入您的昵称',
                icon: 'none',
                duration: 1000
            })
            return false;
        }
        if ((this.data.xm == 'sk') || (this.data.xm == 'sydw') || (this.data.xm == 'jztg') || (this.data.xm == 'fyjcy') || (this.data.xm == 'all')) {
            if (this.data.index3 == 0) {
                xhs.showToast({
                    title: '请选择岗位',
                    icon: 'none',
                    duration: 1000
                })
                return false;
            }
        }
        if ((this.data.nj == 'y')) {
            if (this.data.index4 == 0) {
                xhs.showToast({
                    title: '请选择年级',
                    icon: 'none',
                    duration: 1000
                })
                return false;
            }
        }
        if ((this.data.iszhuanye == 'y')) {
            if (!this.data.zhuanye) {
                xhs.showToast({
                    title: '请输入专业',
                    icon: 'none',
                    duration: 1000
                })
                return false;
            }
        }
        this.clickfnAfter()
    },
    // 注册
    async registerCX() {
        var phonegsd = null
        const { getIdentity, myPhone, title, name } = this.data;
        if (!getIdentity.zzid && getIdentity.fenbu == '河北') {
            phonegsd = await app.methods.get_phone_attribution(myPhone)
        }
        if (phonegsd && phonegsd.province != '河北') var thisRandom = parseInt(Math.random() * 10);
        let data = {
            phone: myPhone,
            gonghao: getIdentity.crm != '' ? getIdentity.crm : getIdentity.username,
            fenxiao: getIdentity.fenxiao,
            xulieName: getIdentity.xulie_name,
            realname: getIdentity.realname,
            laiyuan: title,
            name: name,
            isagree: 'true',
            channel: 122,
            c2: '小程序对接',
            remark: `小程序：河北中公，actid：${this.data.form}，推广码：${getIdentity.crm != "" ? getIdentity.crm : getIdentity.username}`,
            adr: this.data.adr[this.data.index1],
            xianqu: this.data.xianqu[this.data.index2],
            gwlb: this.data.gangwei[this.data.index3],
            orgn: phonegsd ? phonegsd.province == '河北' ? getIdentity.orgn = app.globalData.config.zzidAerpdqm[phonegsd.city].zzid : app.globalData.config.zzidAerpdqm[app.globalData.config.zzidAerpdqm['random'][thisRandom]].zzid : getIdentity.zzid,
            erpdqm: phonegsd ? phonegsd.province == '河北' ? getIdentity.orgn = app.globalData.config.zzidAerpdqm[phonegsd.city].erpdqm : app.globalData.config.zzidAerpdqm[app.globalData.config.zzidAerpdqm['random'][thisRandom]].erpdqm : getIdentity.erpdqm,
            project: this.data.gangwei[this.data.index3],
        }
        if ((this.data.nj == 'y')) {
            data.nianji = this.data.nianji[this.data.index4]
        }
        if ((this.data.iszhuanye == 'y')) {
            data.zhuanye = this.data.zhuanye
        }
        zg99Request({
            url: `/index/chaxun/register/?actid=${this.data.form}&callback=&`,
            method: 'GET',
            dataType: 'jsonp',
            data: {
                ...data,
                shijian: Date.parse(new Date()) / 1000
            },
        }).then(res => {
            let diyici = app.methods.getAPIReturn(res);
            console.log(diyici)
            if (this.data.notice != null && this.data.notice != '' && this.data.notice != undefined) {
                xhs.showModal({
                    title: '提示',
                    content: this.data.notice,
                    showCancel: false,
                    success: ((res) => {
                        if (res.confirm) {
                            this.goLink()
                        }
                    })
                })
            } else {
                xhs.showToast({
                    title: '预约成功！',
                    icon: 'success',
                    duration: 2000
                })
                setTimeout(function () {
                    this.goLink()
                }, 3000)
            }
        })
    },
    // 更新
    async updateuser() {
        let zjz = this.data.user;
        let user = zjz.user;
        let thisLy = user.laiyuan;
        if ((user.gonghao == '无') || (user.gonghao == '') || (user.gonghao == '') || (user.gonghao == null)) {
            user.gonghao = this.data.getIdentity.crm != '' ? this.data.getIdentity.crm : this.data.getIdentity.username;
            user.xulieName = this.data.getIdentity.xulie_name;
            user.realname = this.data.getIdentity.realname;
        }
        if ((user.fenxiao == '无') || (user.fenxiao == '') || (user.fenxiao == '') || (user.fenxiao == null)) {
            user.fenxiao = this.data.getIdentity.fenxiao;
            user.orgn = this.data.getIdentity.orgn;
            user.erpdqm = this.data.getIdentity.erpdqm;
        }
        if (!thisLy) {
            user.laiyuan = this.data.title
        } else if (thisLy.indexOf(this.data.title) < 0) {
            user.laiyuan = thisLy + ',' + this.data.title
        }
        if (this.data.nj == 'y') {
            user.nianji = this.data.nianji[this.data.index4]
        }
        if (this.data.iszhuanye == 'y') {
            user.zhuanye = this.data.zhuanye
        }
        zg99Request({
            url: `/index/chaxun/updateuser?actid=${this.data.form}&callback=&`,
            dataType: "jsonp",
            method: "GET",
            data: {
                ...user,
                shijian: Date.parse(new Date()) / 1000
            },
        }).then(res => {
            let diyici = app.methods.getAPIReturn(res);
            console.log(diyici)
            if (this.data.notice != null && this.data.notice != '' && this.data.notice != undefined) {
                xhs.showModal({
                    title: '提示',
                    content: this.data.notice,
                    showCancel: false,
                    success: ((res) => {
                        if (res.confirm) {
                            this.goLink()
                        }
                    })
                })
            } else {
                xhs.showToast({
                    title: '预约成功！',
                    icon: 'success',
                    duration: 2000
                })
                setTimeout(function () {
                    this.goLink()
                }, 3000)
            }
        })
    },
    // 点击提交最后阶段
    async clickfnAfter(){
        this.setData(await app.methods.getphonestatusCX(this.data.myPhone, this.data.form, 'chaxun'))
        if (!this.data.user) {
            await this.registerCX()
        } else {
            await this.updateuser()
        }
    },
    // 成功后跳转
    goLink() {
        if (this.data.url) {
            let url = this.data.url;
            if (this.data.appid) {
                let {
                    owner,
                    orgn,
                    erp
                } = this.data.getIdentity
                let {
                    url,
                    appid
                } = this.data;
                erp = erp ? erp : 12;
                orgn = orgn ? orgn : 13;
                owner = owner ? owner : 20588;
                if (url.indexOf('&') >= 0) {
                    url = url.substring(0, url.indexOf('&'))
                }
                xhs.navigateToMiniProgram({
                    appId: appid,
                    path: `${url}&owner=${owner}&orgn=${orgn}&erp=${erp}`,
                    extraData: {
                        foo: 'bar' //需要传递给目标小程序的数据，目标小程序可在 App.onLaunch，App.onShow 中获取到这份数据
                    },
                    envVersion: 'release', //要打开的小程序版本。仅在当前小程序为开发版或体验版时此参数有效。如果当前小程序是正式版，则打开的小程序必定是正式版。
                    success(res) {
                        // 打开成功
                    }
                })
            } else if (url.indexOf('pages/index/index') >= 0) {
                xhs.switchTab({
                    url: '/pages/index/index?fenxiao=' + this.data.options.fenxiao + '&gonghao=' + this.data.options.gonghao,
                })
            } else if ((url.indexOf('pages') >= 0) || (url.indexOf('package') >= 0)) {
                xhs.navigateTo({
                    url: url + '&fenxiao=' + this.data.options.fenxiao + '&gonghao=' + this.data.options.gonghao,
                })
            } else if (url.indexOf('https') >= 0) {
                xhs.navigateTo({
                    url: '/packageB/gg/gg?link=' + url,
                    // url: '/pages/wxArticle/wxArticle?src=' + url + '&title=' + this.data.title,
                })
            }
        }
    },
    closeSetModel() {
        this.setData({
            isShowSetModel: false
        })
        this.clickfnAfter()
    },
    openSetCallback(){
        this.setData({
            isShowSetModel: false
        })
    },
    async user_login(e){
        if(typeof e.detail == 'boolean') {
            this.setData({
                isShowAuth: e.detail
            })
        } else {
            this.setData({
                myPhone: e.detail
            })
        }
    },
    /* 用户点击右上角分享 */
    onShareAppMessage: function () {
        let { fx = 'hbwtb', gh = 'zcj37368', id } = this.data.options;
        console.log(fx, gh, id)
        console.log(`/pages/cjcx/cjcx?id=${id}&fx=${fx}&gh=${gh}`)
        return {
          // title: '1V1职业规划咨询',
          path: `/pages/cjcx/cjcx?id=${id}&fx=${fx}&gh=${gh}`,
          imageUrl: ''
        }
    },
    /* 用户点击右上角分享 - 朋友圈 */
    onShareTimeline: function () {}
})